// pages/collection/collection.js
let api = require("../../api/api.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userFav: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    api.userFav().then(res=>{
      console.log(res)
      let userFavList = []
      for(let i = 0; i < res.data.length; i++){
        userFavList.push(res.data[i].course)
      }
      that.setData({ userFav: userFavList })
      console.log(that.data.userFav)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  remove:function(e){
    console.log(e)
    let course_id = e.target.dataset.index
    let index = -1;
    let index_storage = -1;

    // 缓存中的favList
    let userFavList = wx.getStorageSync("userFav")

    for(let i = 0; i < userFavList.length; i++){
      if(userFavList[i].id == course_id){
        index_storage = i
        break;
      }
    }

    for(let i = 0; i < this.data.userFav.length; i ++){
      if(this.data.userFav[i].id == course_id){
        index = i 
      }
    }
    let that = this;
    wx.showModal({
      title: '提示',
      content: '是否移除收藏',
      success:function(res){
        if(res.confirm){
          api.removeUserFav(course_id).then(res=>{
            let favList = that.data.userFav;
            favList.splice(index, 1)
            that.setData({ userFav: favList })
            userFavList.splice(index_storage, 1)
            wx.setStorageSync('userFav', userFavList)
          })      
        }else{
          console.log("cancel")
        }
        wx.hideLoading()
      }
    })

  }
})